<template>
	<div>
		<!-- 配置题目弹窗  -->
		<el-card shadow="never" class="mainCard" v-loading="loading">
      <div style="width: 100%; height: 40px;">
      <el-button
        type="warning"
        size="small"
        link
        style="float: right; margin-left: 10px;"
        @click="reback()"
        >返 回</el-button>
      <el-button
        v-if="details.pageQuestions && details.pageQuestions.length != 0"
        type="primary"
        size="small"
        link
        style="float: right;"
        @click="sortOptionList()"
        >更新排序</el-button>
      
      </div>
			<el-card class="topCard">
				<el-form ref="userFormRef1" :model="details" :row-class-name="tableRowClassName" label-width="70px">
					<el-form-item label="问卷题目" prop="questions">
						<el-table
							row-key="n"
							:cell-style="cellStyle"
							:tree-props="{ children: 'children' }"
							:data="details.pageQuestions"
							:show-header="false"
						>
							<el-table-column label="" width="80" prop="dataIndex" />
							<el-table-column prop="title" label=""></el-table-column>
							<el-table-column fixed="right" label="操作" min-width="350" width="350">
								<template #default="scope">
									<template v-if="scope.row.surveyItemType == 'QUESTION'">
										<el-tag type="warning" style="cursor: pointer" @click="openSurveyQuestionEditDialog(scope)" v-if="scope.row.mode == 'QUESTION'"
											>配置</el-tag
										>
										<el-tag type="info" style="cursor: pointer; margin-left: 10px" @click="upMove(scope)">上移</el-tag>
										<el-tag type="info" style="cursor: pointer; margin-left: 10px" @click="downMove(scope)">下移</el-tag>
										<el-tag type="success" style="cursor: pointer; margin-left: 10px" @click="openEditQuestionDialog(scope)">编辑</el-tag>
										<el-tag type="danger" style="cursor: pointer; margin-left: 10px" @click="delOption(scope.row.id)">移除</el-tag>
									</template>
									<template v-if="scope.row.surveyItemType == 'OPTION'">
										<el-tag type="" style="cursor: pointer" @click="configBranchQuestions(scope)">分支问题</el-tag>
										<el-tag type="warning" style="cursor: pointer; margin-left: 5px" @click="openOptionTextDialog(scope.row)">选项填空</el-tag>
									</template>
									<template v-if="scope.row.surveyItemType == 'PAGE'">
										<span>页标签</span>
										<el-tag type="info" style="cursor: pointer; margin-left: 10px" @click="upMove(scope)">上移</el-tag>
										<el-tag type="info" style="cursor: pointer; margin-left: 10px" @click="downMove(scope)">下移</el-tag>
										<el-tag type="success" style="cursor: pointer; margin-left: 10px" @click="openEditQuestionDialog(scope)">编辑</el-tag>
										<el-tag type="danger" style="cursor: pointer; margin-left: 10px" @click="delOption(scope.row.id)">移除</el-tag>
									</template>
								</template>
							</el-table-column>
						</el-table>
					</el-form-item>
				</el-form>
			</el-card>
      
			<el-card class="bottomCard">
				<el-table
					ref="multipleTable"
					v-loading="loading"
					:data="questionList.filter((data) => !questionSearchParam || data.title.toLowerCase().includes(questionSearchParam.toLowerCase()))"
					highlight-current-row
					border
				>
					<el-table-column label="题目标题" prop="title" />
					<el-table-column label="题目模式" prop="mode" />
					<el-table-column label="题目类型" prop="typeText" />
					<el-table-column align="right">
						<template slot="header" slot-scope="scope">
							<el-input v-model="questionSearchParam" size="mini" placeholder="输入关键字搜索" />
						</template>
						<template slot-scope="scope">
							<el-button :disabled="!scope.row.selectButton" type="warning" size="small" link @click="addOption(scope.row.id)"
								><i class="el-icon-edit"></i> 添加至问题</el-button
							>
						</template>
					</el-table-column>
				</el-table>

				<template #footer>
					<div class="dialog-footer">
						<el-button @click="closeQuestionsDialog">取 消</el-button>
					</div>
				</template>
			</el-card>
		</el-card>

		<el-dialog :visible.sync="questionConfigtDialogVisble" width="600px" title="问卷题目配置">
			<el-form ref="form" :model="surveyQuestionForm" label-width="120px">
				<el-form-item label="题目类型" v-if="surveyQuestionData.type == 'TEXTAREA'">
					<el-select v-model="surveyQuestionForm.inputType" placeholder="请选择输入类型" size="medium">
						<el-option label="普通文本" value="STRING"></el-option>
						<el-option label="日期" value="DATE"></el-option>
						<el-option label="数字" value="NUMBER"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="数字限制" v-if="surveyQuestionData.type == 'TEXTAREA' && surveyQuestionForm.inputType == 'NUMBER'">
					<el-col :span="10">
						<el-input size="medium" placeholder="请输入最小值" v-model="surveyQuestionForm.min"></el-input>
					</el-col>
					<el-col :span="10">
						<el-input size="medium" placeholder="请输入最大值" v-model="surveyQuestionForm.max" style="margin-left: 10px"> </el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="所属页">
					<el-select v-model="surveyQuestionForm.pageQuestionId" placeholder="请选择所属页" size="medium">
						<el-option v-for="item in pageQuestionList" :label="item.title" :value="item.id" :key="item.id" v-show="item.mode == 'PAGE'"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitSurveyQuestion">确 定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog :visible.sync="optionTextDialogVisble" width="450px" title="选项是否需要填空">
			<template>
				<el-radio v-model="optionTextRadio" :label="true">选项需要填空</el-radio>
				<el-radio v-model="optionTextRadio" :label="false">选项不需要填空</el-radio>
			</template>
			<el-button type="warning" size="small" link @click="changeOptionTextFlag()"><i class="el-icon-edit"></i> 确 认</el-button>
		</el-dialog>

		<el-dialog width="600px" :visible.sync="optionSelectQuestionVisible" title="选择分支题目">
			<el-button @click="addBranchQuestions">添加分支题目</el-button>
			<el-table
				ref="multipleTable"
				v-loading="loading"
				:data="
					optionSelectQuestionArr.filter(
						(data) => !optionSelectQuestionParam || data.title.toLowerCase().includes(optionSelectQuestionParam.toLowerCase())
					)
				"
				highlight-current-row
				height="250"
				border
				@selection-change="handleSelectionQuestionChange"
				style="margin-top: 20px"
			>
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="题目标题" prop="title" />
				<el-table-column label="题目类型" prop="typeText" />
				<el-table-column align="right">
					<template slot="header">
						<el-input v-model="optionSelectQuestionParam" size="mini" placeholder="输入关键字搜索" />
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>

		<el-dialog width="600px" :visible.sync="editQuestionDialog" title="编辑题目（页）标题">
			<el-form ref="formEditQuestion" :model="editQuestionForm" label-width="120px">
				<el-form-item label="题目标题">
					<el-input size="medium" placeholder="请输入要修改的题目标题" v-model="editQuestionForm.title"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="editQuestionSubmit">保 存</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script>
import surveyApi from '@/api/aliyun/questionnaire/survey';
import questionApi from '@/api/aliyun/questionnaire/question';
export default {
	name: 'surveyConfigIndex',
	props: {
		checkedSurvey: {
			type: Object,
			default: {},
		},
	},
	data() {
		return {
			loading: false,
			ids: [],
			questionsDialogVisible: false,
			dialog: {},

			typeMap: {
				EXCLUSIVE_CHOICE: '单选',
				MULTIPLE_CHOICE: '多选',
				TEXTAREA: '填空',
			},
			details: {},
			questionList: [],
			questionSearchParam: '',

			optionSelectQuestionArr: [],
			optionSelectQuestionParam: '',
			optionSelectQuestionVisible: false,
			branchQuestionArr: [],
			branchQuestionStr: '',
			branchQuestionOrginId: '',
			branchQuestionOptionId: '',

			optionTextDialogVisble: false,
			optionTextData: {},
			optionTextRadio: '',

			questionConfigtDialogVisble: false,

			surveyQuestionForm: {},
			surveyQuestionData: {},

			pageQuestionList: [],
			questionIndexMap: {},

			editQuestionDialog: false,
			editQuestionForm: {},
		};
	},
	mounted() {
		this.init();
	},
	methods: {
    reback () {
      this.$emit("close");
    },
		editQuestionSubmit() {
			let surveyId = this.checkedSurvey.id;
			questionApi.updateTitle(this.editQuestionForm).then((res) => {
				this.$message({ message: '问卷题目标题修改成功！', type: 'success' });
				this.editQuestionDialog = false;
				this.resultDetail(surveyId);
			});
		},
		openEditQuestionDialog(row) {
			this.editQuestionDialog = true;
			this.editQuestionForm = row.row;
		},
		submitSurveyQuestion() {
			let data = this.surveyQuestionData;
			let questionId = data.id;
			let surveyId = this.checkedSurvey.id;
			let surveyQuestionForm = this.surveyQuestionForm;
			surveyQuestionForm.textLimit = JSON.stringify({
				min: surveyQuestionForm.min,
				max: surveyQuestionForm.max,
			});
			surveyApi.configSurveyQuestionExt(surveyId, questionId, surveyQuestionForm).then((res) => {
				this.$message({ message: '问卷题目配置成功！', type: 'success' });
				this.questionConfigtDialogVisble = false;
				this.resultDetail(surveyId);
			});
		},
		openSurveyQuestionEditDialog(scope) {
			this.questionConfigtDialogVisble = true;
			this.surveyQuestionData = scope.row;
			this.surveyQuestionForm = {};
			surveyApi.findQuestionConfig(this.checkedSurvey.id, this.surveyQuestionData.id).then((res) => {
				let data = res.data;
				let result = {};
				if (data.textLimit) {
					result = JSON.parse(data.textLimit);
				}
				result.inputType = data.inputType;
				this.surveyQuestionForm = result;
			});
		},
		tableRowClassName({ row, rowIndex }) {
			return 'warning-row';
		},
		openOptionTextDialog(row) {
			this.optionTextDialogVisble = true;
			this.optionTextData = row;
			this.optionTextRadio = row.showText;
		},
		changeOptionTextFlag() {
			let showText = this.optionTextRadio;
			let data = this.optionTextData;
			questionApi.configOptionShowText(data.pId, data.id, showText).then((res) => {
				this.optionTextDialogVisble = false;
				this.$message({ message: '选项是否需要填空成功！', type: 'success' });
			});
		},
		addBranchQuestions() {
			let params = [];
			this.branchQuestionArr.forEach((v) => {
				params.push(v.id);
			});
			questionApi.configBranchQuestions(this.branchQuestionOrginId, this.branchQuestionOptionId, params).then((res) => {
				this.optionSelectQuestionVisible = false;
				this.$message({ message: '选项分支题目配置成功！', type: 'success' });
			});
		},
		handleSelectionQuestionChange(vals) {
			this.branchQuestionArr = vals;
			vals.forEach((v) => {
				this.branchQuestionStr += v.title + '\n';
			});
		},
		configBranchQuestions(scope) {
      this.branchQuestionOptionId = scope.row.id;
			this.branchQuestionOrginId = scope.row.pId;
      if (!scope.row.pIndex) {
        let index = this.questionIndexMap.get(scope.row.pId).index;
        console.log(index, scope)
        let arr =  this.pageQuestionList.slice(index + 1);
        let that = this;
        arr.forEach((v) => {
          v.typeText = that.typeMap[v.type];
        });
        this.optionSelectQuestionArr = arr;
        this.optionSelectQuestionVisible = true;
        return;
      }
			
			let index = scope.row.pIndex;
			let pageIndex = scope.row.pageIndex;
      let pageList = [];
      this.pageQuestionList.forEach(v => {
        if (v.mode === 'PAGE') {
          pageList.push(v);
        }
      })
			let arr = pageList[pageIndex].children.slice(index);
			let that = this;
			arr.forEach((v) => {
				v.typeText = that.typeMap[v.type];
			});
			this.optionSelectQuestionArr = arr;
			this.optionSelectQuestionVisible = true;
		},
		addOption(questionId) {
			let surveyId = this.checkedSurvey.id;
			let questionIds = [questionId];
			let that = this;
			surveyApi.configQuestions(surveyId, questionIds).then((res) => {
				this.$message({ message: '问卷题目添加成功！', type: 'success' });
				this.resultDetail(surveyId);
			});
		},
		delOption(questionId) {
			let surveyId = this.checkedSurvey.id;
			let questionIds = [questionId];
			surveyApi.deleteQuestions(surveyId, questionIds).then((res) => {
				this.$message({ message: '问卷题目删除成功！', type: 'success' });
				this.resultDetail(surveyId);
			});
		},
		downMove(o) {
			let indexObj = this.questionIndexMap.get(o.row.id);
			let index = indexObj.index;
			let questions = [];
			if (indexObj.level) {
				questions = this.details.pageQuestions;
			} else {
				questions = this.details.pageQuestions[indexObj.pageIndex].children;
			}

			if (index == questions.length - 1) {
				this.$message.error('当前题目已经是最后一个，不能移动！');
				return;
			}
			let nextQuestionId = questions[index + 1].id;
			let nextIndexObj = this.questionIndexMap.get(nextQuestionId);
			questions.splice(index, 1, ...questions.splice(index + 1, 1, questions[index]));
			if (indexObj.level) {
				this.$set(this.details, 'pageQuestions', questions);
			} else {
				this.$set(this.details.pageQuestions[indexObj.pageIndex], 'children', questions);
			}
			this.questionIndexMap.set(o.row.id, nextIndexObj);
			this.questionIndexMap.set(nextQuestionId, indexObj);
		},
		upMove(o) {
			let indexObj = this.questionIndexMap.get(o.row.id);
			let index = indexObj.index;
			let questions = [];
			if (indexObj.level) {
				questions = this.details.pageQuestions;
			} else {
				questions = this.details.pageQuestions[indexObj.pageIndex].children;
			}
			if (index == 0) {
				this.$message.error('当前题目已经是第一个，不能移动！');
				return;
			}
			let nextQuestionId = questions[index - 1].id;
			let nextIndexObj = this.questionIndexMap.get(nextQuestionId);
			questions.splice(index - 1, 1, ...questions.splice(index, 1, questions[index - 1]));
			if (indexObj.level) {
				this.$set(this.details, 'pageQuestions', questions);
			} else {
				this.$set(this.details.pageQuestions[indexObj.pageIndex], 'children', questions);
			}
			this.questionIndexMap.set(o.row.id, nextIndexObj);
			this.questionIndexMap.set(nextQuestionId, indexObj);
		},
		sortOptionList() {
			let surveyId = this.checkedSurvey.id;
			let pages = this.details.pageQuestions;
			let questionIds = [];
			pages.forEach((page) => {
				let questions = page.children;
				if (questions && questions.length != 0) {
					questions.forEach((v) => {
						questionIds.push(v.id);
					});
				}
				questionIds.push(page.id);
			});

			surveyApi.sortQuestions(surveyId, questionIds).then((res) => {
				this.$message({ message: '问卷题目排序成功！', type: 'success' });
				this.resultDetail(surveyId);
			});
		},
		parseQuestionList(questionList, questionIds, pageIndex, questionIndexMap) {
			let resultList = [];
			let dIndex = 1;
			questionList.forEach((d) => {
				questionIndexMap.set(d.id, {
					pageIndex: pageIndex,
					index: dIndex - 1,
				});
				d.dataIndex = dIndex++;
				d.n = d.id + d.title;
				d.surveyItemType = 'QUESTION';
				let dChildren = [];
				if (d.options) {
					d.options.forEach((dop) => {
						dop.n = d.id + '_' + dop.id + '_' + dop.title;
						dop.pIndex = d.dataIndex;
						dop.pageIndex = pageIndex;
						dop.pId = d.id;
						dop.showText = dop.showText ? dop.showText : false;
						dop.surveyItemType = 'OPTION';
						dChildren.push(dop);
					});
				}
				d.children = dChildren;
				questionIds.push(d.id);
				resultList.push(d);
			});
			return resultList;
		},

		resultDetail(id) {
			let that = this;
			let questionIndexMap = new Map();
			surveyApi.detail(id).then((res) => {
				let pageQuestions = res.data.pageQuestions;
				let pageQuestionMap = {};
				let pageIndex = 0;
				let questionIds = [];
				let questionIndex = 0;
				pageQuestions.forEach((v) => {
					let vChildrens = v.questions;
					if (v.mode == 'PAGE') {
						v.children = that.parseQuestionList(vChildrens, questionIds, pageIndex++, questionIndexMap);
						pageQuestionMap[v.id] = v;
						v.n = 'PAGE_' + v.id;
						v.surveyItemType = 'PAGE';
					} else {
						v.surveyItemType = 'QUESTION';
            v.n = 'QUESTION_' + v.id;
            let dChildren = [];
            if (v.options.length > 0) {
              v.options.forEach((dop) => {
                dop.n = v.id + '_' + dop.id + '_' + dop.title;
                dop.pIndex = v.dataIndex;
                dop.pageIndex = pageIndex;
                dop.pId = v.id;
                dop.showText = dop.showText ? dop.showText : false;
                dop.surveyItemType = 'OPTION';
                dChildren.push(dop);
              });
              v.children = dChildren;
            }
					}
					questionIndexMap.set(v.id, {
						pageIndex: 0,
						index: questionIndex++,
						level: 'top',
					});
					questionIds.push(v.id);
				});
				that.pageQuestionList = pageQuestions;
				// 处理题目以及选项
				//let questionList = this.parseQuestionList(res.data.questions, questionIds, 0, questionIndexMap)
				that.questionIndexMap = questionIndexMap;

				res.data.pageQuestions = pageQuestions;
				that.details = res.data;
			});
		},

		init() {
			this.questionsDialogVisible = true;
			let row = this.checkedSurvey;
			let that = this;
			let questionIndexMap = new Map();
			this.loading = true;
			surveyApi.detail(row.id).then((res) => {
				let pageQuestions = res.data.pageQuestions;
				let pageQuestionMap = {};
				let pageIndex = 0;
				let questionIds = [];
				let questionIndex = 0;
				pageQuestions.forEach((v) => {
					let vChildrens = v.questions;
					if (v.mode == 'PAGE') {
						v.children = that.parseQuestionList(vChildrens, questionIds, pageIndex++, questionIndexMap);
						pageQuestionMap[v.id] = v;
						v.n = 'PAGE_' + v.id;
						v.surveyItemType = 'PAGE';
					} else {
						v.surveyItemType = 'QUESTION';
            v.n = 'QUESTION_' + v.id;
            let dChildren = [];
            console.log(v.options)
            if (v.options.length > 0) {
              v.options.forEach((dop) => {
                dop.n = v.id + '_' + dop.id + '_' + dop.title;
                dop.pIndex = v.dataIndex;
                dop.pageIndex = pageIndex;
                dop.pId = v.id;
                dop.showText = dop.showText ? dop.showText : false;
                dop.surveyItemType = 'OPTION';
                dChildren.push(dop);
              });
              v.children = dChildren;
            }
					}
					questionIndexMap.set(v.id, {
						pageIndex: 0,
						index: questionIndex++,
						level: 'top',
					});
					questionIds.push(v.id);
				});
				this.pageQuestionList = pageQuestions;
				// 处理题目以及选项
				//let questionList = this.parseQuestionList(res.data.questions, questionIds, 0, questionIndexMap)
				this.questionIndexMap = questionIndexMap;

				res.data.pageQuestions = pageQuestions;
				this.details = res.data;

				questionApi.list().then((res1) => {
					this.questionList = res1.data;
					this.questionList.forEach((v) => {
						v.typeText = that.typeMap[v.type];
						if (questionIds.indexOf(v.id) != -1) {
							v.selectButton = false;
						} else {
							v.selectButton = true;
						}
					});
					this.loading = false;
				});
			});
		},
		closeQuestionsDialog() {
			this.questionsDialogVisible = false;
		},
		cellStyle({ row, column, rowIndex, columnIndex }) {
			if (row.surveyItemType == 'PAGE') {
				return {
					'font-weight': '600',
				};
			}
		},
	},
};
</script>

<style scoped>
.mainCard {
	height: calc(100vh - 120px);
	overflow: hidden;
}
.topCard {
  height: 600px;
  overflow: auto;
}
.bottomCard {
  height: calc(100vh - 720px);
  overflow: auto;
}
.surveyConfig /deep/ .el-dialog__body {
	height: 800px;
	overflow: auto;
}

.block {
	margin-top: 10px;
	float: right;
	margin-bottom: 10px;
}
.el-table .warning-row {
	background: oldlace;
}
</style>
